package cn.itcast.form;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.util.Base64;

import com.sun.mail.util.BASE64EncoderStream;
// 产生表单
public class FormServlet extends HttpServlet {



	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		response.setContentType("text/html;charset=UTF-8");

		TokenProcesssor tp = TokenProcesssor.getInstance();
		String token = tp.generateToken();
		
		request.getSession().setAttribute("token", token);
		
		request.getRequestDispatcher("/day07/form.jsp").forward(request, response);

	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request, response);
		response.setContentType("text/html;charset=UTF-8");

	}

}



class TokenProcesssor{

	/*
	 *  1.构造方法私有
	 *  2 .自己创建
	 *  3. 对外暴露一个方法.允许获取 上面创建的对象
	 */

	private TokenProcesssor(){}

	private  static final  TokenProcesssor instance =new TokenProcesssor();

	public static TokenProcesssor getInstance(){
		return  instance;
	}

	public String generateToken(){

		String token =System.currentTimeMillis()+new Random().nextInt()+"";

		try {
			MessageDigest md = MessageDigest.getInstance("md5");
			byte[] md5 = md.digest(token.getBytes());

			//			return new String(md5);

			//base64 编码
			BASE64EncoderStream encoderStream = new BASE64EncoderStream(new ByteArrayOutputStream());
			//			return base64.encode(md5)

			return new String(encoderStream.encode(md5));




		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;



	}

}
